package com.cuiweiyou.mysqljdbc.activity;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.cuiweiyou.mysqljdbc.R;
import com.cuiweiyou.mysqljdbc.R.id;
import com.cuiweiyou.mysqljdbc.R.layout;
import com.cuiweiyou.mysqljdbc.task.MysqlConnectionTask;
import com.cuiweiyou.mysqljdbc.task.MysqlResultSetTask;
import com.cuiweiyou.mysqljdbc.util.MysqlUtil;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;

public class MainActivity extends Activity{

	private Button mButton;
	private Spinner mSpinner;
	private String[] sqls;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		initButton();
		initSpinner();
	}

	private void initButton() {
		mButton = (Button) findViewById(R.id.connectbtn);
		mButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				new MysqlConnectionTask().execute();
			}
		});
	}

	private void initSpinner() {
		sqls = new String[] { "select * from tb_user;", "select username, useraddr from tb_user where userage > 30;", "", "", "" };
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, sqls);
		mSpinner = (Spinner) findViewById(R.id.sqlspinner);
		mSpinner.setAdapter(adapter);
		mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				Log.e("ard", "选中的sql语句：" + mSpinner.getSelectedItem().toString());
				if(null != MysqlUtil.conn && !"".equals(sqls[position])) {
					new MysqlResultSetTask().execute(sqls[position]);
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
			}
		});
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		try {
			MysqlUtil.destoryConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
